const express = require('express');
const cors = require('cors');
const sensorRouter = require('./routes/sensor');
const cameraRouter = require('./routes/camera');

const app = express();

// 全局 CORS 配置
app.use(cors({
  origin: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true
}));

app.use(express.json());

// 请求日志中间件
app.use((req, res, next) => {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
  next();
});

// API 路由
app.use('/api/sensor', sensorRouter);
app.use('/api/cameras', cameraRouter);

// 404 处理
app.use((req, res) => {
  console.log('404 Not Found:', req.url);
  res.status(404).json({
    status: 404,
    message: '接口不存在',
    path: req.url
  });
});

const PORT = 8080;
const server = app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

// 优雅退出
process.on('SIGTERM', () => {
  console.log('SIGTERM signal received: closing HTTP server');
  server.close(() => {
    console.log('HTTP server closed');
    process.exit(0);
  });
}); 